package com.hskn.hss.module.tlrepaircfg.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hskn.hss.core.annotation.SysLog;
import com.hskn.hss.core.domain.BaseEntity;
import com.hskn.hss.core.enums.BusinessType;
import com.hskn.hss.core.utils.file.FileTypeUtils;
import com.hskn.hss.core.utils.poi.ExcelUtil;
import com.hskn.hss.entity.AjaxResult;
import com.hskn.hss.exception.ExcelReaderDataException;
import com.hskn.hss.exception.HssException;
import com.hskn.hss.module.common.ienum.ExcelTypeEnum;
import com.hskn.hss.module.common.to.ExcelReaderTO;
import com.hskn.hss.module.costdictitem.entity.CostDictItem;
import com.hskn.hss.module.costdictitem.service.ICostDictItemService;
import com.hskn.hss.module.depart.entity.SysDepart;
import com.hskn.hss.module.depart.service.ISysDepartService;
import com.hskn.hss.module.tlcar.entity.TlCar;
import com.hskn.hss.module.tlcar.service.ITlCarService;
import com.hskn.hss.module.tlcartype.entity.TlCarType;
import com.hskn.hss.module.tlcartype.service.ITlCarTypeService;
import com.hskn.hss.module.tloilcostcfg.mapper.TlOilcostCfgMapper;
import com.hskn.hss.module.tlopetation.entity.TlOperation;
import com.hskn.hss.module.tlrepaircfg.entity.TlRepairCfg;
import com.hskn.hss.module.tlrepaircfg.mapper.TlRepairCfgMapper;
import com.hskn.hss.module.tlrepaircfg.service.ITlRepairCfgService;
import com.hskn.hss.module.tlrepaircfg.to.TlRepairCfgListTO;
import com.hskn.hss.module.tlrepaircfg.vo.TlRepairCfgExecelInVO;
import com.hskn.hss.module.tlrepaircfg.vo.TlRepairCfgExecelVO;
import com.hskn.hss.module.user.entity.User;
import com.hskn.hss.module.user.service.IUserService;
import com.hskn.hss.to.ForIdsTO;
import com.hskn.hss.utils.StringUtils;
import com.hskn.hss.utils.Tools;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author hskn
 * @since 2021-05-05
 */
@Slf4j
@RestController
@RequestMapping("/hss/tlrepaircfg")
@Api(tags = {"-tl_repair_cfg"}, description = "车辆维修费")
public class TlRepairCfgController {

    @Autowired
    private ITlRepairCfgService tlRepairCfgService;
    @Autowired
    private ISysDepartService departService;
    @Autowired
    private ICostDictItemService costDictItemService;
    @Autowired
    private ITlCarService carService;
    @Autowired
    private ITlCarTypeService carTypeService;
    @Autowired
    private IUserService userService;

    /***
     * 新增
     * @param request
     * @return
     */
    @SysLog(businessType = BusinessType.INSERT, tableName = "tl_repair_cfg", bean = TlRepairCfg.class, beanMapper = TlRepairCfgMapper.class, names = "carnumid")
    @RequestMapping(value = "insert", method = RequestMethod.POST)
    public AjaxResult<Object> insert(HttpServletRequest request) {
        try {
            JSONObject params = JSON.parseObject(Tools.getBody(request));
            return tlRepairCfgService.insert(params);
        } catch (HssException e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("操作失败，请稍后再试");
        }
    }

    /**
     * 修改
     * @param request
     * @return
     */
    @SysLog(businessType = BusinessType.UPDATE, tableName = "tl_repair_cfg", idKey = "id", bean = TlRepairCfg.class, beanMapper = TlRepairCfgMapper.class, names = "carnumid")
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public AjaxResult<Object> update(HttpServletRequest request) {
        try {
            JSONObject params = JSON.parseObject(Tools.getBody(request));
            return tlRepairCfgService.update(params);
        } catch (HssException e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("操作失败，请稍后再试");
        }
    }

    /***
     * 删除
     * @param forIdsTO
     * @return
     */
    @SysLog(businessType = BusinessType.DELETE, tableName = "tl_repair_cfg", idKey = "ids", bean = TlRepairCfg.class, beanMapper = TlRepairCfgMapper.class, names = "carnumid")
    @RequestMapping(value = "deleteByid", method = RequestMethod.POST)
    public AjaxResult<Object> deleteByid(@RequestBody @Validated ForIdsTO forIdsTO) {
        try {
            return tlRepairCfgService.deleteByid(forIdsTO);
        } catch (HssException e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("删除失败，请稍后再试");
        }
    }

    /**
     * 根据Id获取
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "getbyid", method = RequestMethod.POST)
    public AjaxResult<Object> getbyid(HttpServletRequest request) {
        JSONObject params = JSON.parseObject(Tools.getBody(request));
        TlRepairCfg tlRepairCfg = null;
        try {
            tlRepairCfg = tlRepairCfgService.getDetailById(params);
            return AjaxResult.success(tlRepairCfg);
        } catch (HssException e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("获取信息失败，请稍后再试");
        }
    }

    /**
     * 获取列表
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "getlist", method = RequestMethod.POST)
    public AjaxResult<Object> getlist(HttpServletRequest request) {
        JSONObject params = JSON.parseObject(Tools.getBody(request));
        try {
            BaseEntity entity = new BaseEntity();
            JSONObject json = tlRepairCfgService.getList(entity, params);
            return AjaxResult.success(json);
        } catch (HssException e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("获取信息失败，请稍后再试");
        }

    }

    /**
     * 车辆维修导入接口
     *
     * @param request
     * @return
     */
//    @SysLog(businessType = BusinessType.INSERT, tableName = "tl_repair_cfg", bean = TlRepairCfg.class, beanMapper = TlRepairCfgMapper.class, names = "carnumid")
    @ApiOperation(value = "车辆维修导入接口", notes = "车辆维修导入")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok")
    })
    @PostMapping("excelReader")
    public AjaxResult excelReader(HttpServletRequest request, @ModelAttribute @Validated ExcelReaderTO excelReaderTo) {
        try {
            MultipartFile file = excelReaderTo.getFiles();
            if (Arrays.stream(ExcelTypeEnum.values()).noneMatch(s -> s.getName().equals(FileTypeUtils.getFileType(file.getOriginalFilename().toLowerCase())))) {
                return AjaxResult.fail("导入文件格式错误");
            }
            InputStream inputStream = new BufferedInputStream(file.getInputStream());
            ExcelUtil<TlRepairCfg> util = new ExcelUtil<TlRepairCfg>(TlRepairCfg.class);
            List<TlRepairCfg> repairCfgList = util.importExcel(inputStream);
            if (repairCfgList.isEmpty()) {
                return AjaxResult.fail("导入内容为空");
            }
            tlRepairCfgService.excelReader(repairCfgList);
            if (tlRepairCfgService.saveBatch(repairCfgList)) {
                return AjaxResult.success();
            } else {
                return AjaxResult.fail("导入失败");
            }
        } catch (ExcelReaderDataException e) {
            return AjaxResult.fail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.fail();
        }
    }

    @ApiOperation(value = "维修导出接口", notes = "维修导出")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = TlRepairCfgExecelVO.class)
    })
    @PostMapping("excelExport")
    public com.hskn.hss.core.domain.AjaxResult excelExport(HttpServletRequest request, @RequestBody TlRepairCfgListTO repairCfgListTO) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
            if((repairCfgListTO.getIds()!=null&&repairCfgListTO.getIds().isEmpty())){
                return com.hskn.hss.core.domain.AjaxResult.error("请选择至少一条数据导出");
            }
            List<TlRepairCfg> repairCfgList = tlRepairCfgService.getTlRepairCfgList(repairCfgListTO, format);
            //工具类实例化
            ExcelUtil<TlRepairCfgExecelVO> util = new ExcelUtil<TlRepairCfgExecelVO>(TlRepairCfgExecelVO.class);
            //数据载体转换
            List<TlRepairCfgExecelVO> tlRepairCfgExecelVOList = new ArrayList<>();
            //构造结果集
            Map<String, SysDepart> departMap = departService.getDepartMap(new QueryWrapper<>());
            Map<String, CostDictItem> costDictItemMap = costDictItemService.getCostDictItemMap(new QueryWrapper<>());
            Map<String, TlCarType> carTypeMap = carTypeService.getCarTypeMap(new QueryWrapper<>());
            Map<String, TlCar> carMap = carService.getCarMap(new QueryWrapper<>());
            Map<String, User> userMap = userService.getUserMap();
            for (TlRepairCfg tlRepairCfg : repairCfgList) {

                    TlCar car = Objects.nonNull(carMap.get(tlRepairCfg.getCarnumid()))?carMap.get(tlRepairCfg.getCarnumid()):new TlCar();
                    TlCarType carType = Objects.nonNull(carTypeMap.get(car.getCartypeid()))?carTypeMap.get(car.getCartypeid()):new TlCarType();
                    User user = Objects.nonNull(userMap.get(car.getDriverid()))?userMap.get(car.getDriverid()):new User();
                    SysDepart depart = Objects.nonNull(departMap.get(car.getCardeptid()))?departMap.get(car.getCardeptid()):new SysDepart();
                    tlRepairCfgExecelVOList.add(TlRepairCfgExecelVO.buildTlRepairCfgExecelVO(tlRepairCfg,
                            Objects.nonNull(car)?car:new TlCar(),
                            Objects.nonNull(carType)?carType:new TlCarType(),
                            Objects.nonNull(user)?user:new User(),
                            Objects.nonNull(depart)?depart:new SysDepart()
                    ));

            }
            //            导出
            return util.exportExcel(tlRepairCfgExecelVOList, "车辆维修");

        } catch (Exception e) {
            e.printStackTrace();
            return com.hskn.hss.core.domain.AjaxResult.error();
        }

    }


    @ApiOperation(value = "车辆维修导出模板接口", notes = "车辆维修模板导出")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = TlRepairCfgExecelInVO.class)
    })
    @PostMapping("excelExportTemplate")
    public com.hskn.hss.core.domain.AjaxResult excelExportTemplate(HttpServletRequest request) {
        try {
            //工具类实例化
            ExcelUtil<TlRepairCfgExecelInVO> util = new ExcelUtil<TlRepairCfgExecelInVO>(TlRepairCfgExecelInVO.class);
            //数据载体转换
            List<TlRepairCfgExecelInVO> repairCfgExecelVoList = new ArrayList<>();
            //导出
            return util.exportExcel(repairCfgExecelVoList, "车辆维修模板");
        } catch (Exception e) {
            e.printStackTrace();
            return com.hskn.hss.core.domain.AjaxResult.error();
        }

    }
}

